<template>
  <div class="invoiceWrap">
    <div class="invoiceBox">
      <div class="tlt">
        <div class="titleH3">
          <i></i>
          <h3>运费发票</h3>
        </div>
        <span @click="addTransInvoice"><i>+</i>新增</span>
      </div>
      <div class="invoiceCont" v-for="(item,index) in transTaxList">
        <ul>
          <li>
            <span>发票号</span>
            <input type="text" v-model="item.invoiceNum">
          </li>
          <li>
            <span>发票代码</span>
            <input type="text" v-model="item.invoiceBoxNum">
          </li>
          <li>
            <span>发票日期</span>
            <input type="text" v-model="item.invoiceDate" @click="openPicker(0,index)">
          </li>
          <li>
            <span>税率</span>
            <input type="text" v-model="transTaxRateStr" class="readonly" readonly value="10%">
          </li>
          <li>
            <span>税额</span>
            <input type="text" v-model="item.invoiceAmount" :change="change(index,0)">
          </li>
        </ul>
        <div class="count">
          发票总额(含税):
          <i>{{(item.invoiceTaxAmount*1).toFixed(2)}}元</i>
        </div>
        <div class="close" @click="removeTransInvoice(index)">×</div>
      </div>
      <div class="upload">
        <h4>运费发票上传</h4>
        <ul class="imgGroup clearfix">
          <li class="add" @click="getUploadPictures(0)">+</li>
          <li v-for="(item,index) in attachmentInvoice" :key="index">
            <!-- <img :src="item.attachmentUrl" v-preview="item.attachmentUrl" alt="加载失败"> -->
            <img class="wc-preview-img" :src="item.attachmentUrl" @click="$preview($event, imgList,index)">
            <div class="dele" @click='removeData(attachmentInvoice,item,index,1)' >×</div>
          </li>
        </ul>
      </div>
    </div>
    <div class="invoiceBox incidental">
      <div class="tlt">
        <div class="titleH3">
          <i></i>
          <h3>杂费发票</h3>
        </div>
        <span @click="addFeeInvoice"><i>+</i>新增</span>
      </div>
      <div class="invoiceCont" v-for="(item,index)  in feeTaxList">
        <ul>
          <li>
            <span>发票号</span>
            <input type="text" v-model="item.invoiceNum">
          </li>
          <li>
            <span>发票代码</span>
            <input type="text" v-model="item.invoiceBoxNum">
          </li>
          <li>
            <span>发票日期</span>
            <input type="text" v-model="item.invoiceDate" @click="openPicker(1,index)">
          </li>
          <li>
            <span>税率</span>
            <input type="text" v-model="feeTaxRateStr" class="readonly" readonly value="10%">
          </li>
          <li>
            <span>税额</span>
            <input type="text" v-model="item.invoiceAmount" :change="change(index,1)">
          </li>
        </ul>
        <div class="count">
          发票总额(含税):
          <i>{{(item.invoiceTaxAmount*1).toFixed(2)}}元</i>
        </div>
        <div class="close" @click="removeFeeInvoice(index)">×</div>
      </div>
      <div class="upload">
        <h4>杂费发票上传</h4>
        <ul class="imgGroup clearfix">
          <li class="add" @click="getUploadPictures(1)">+</li>
          <li v-for="(item,index) in attachmentExtras">
            <img class="wc-preview-img" :src="item.attachmentUrl" alt="加载失败" @click="$preview($event, showExtrasImg,index)">
            <div class="dele" @click='removeData(attachmentExtras,item,index,2)' >×</div>
          </li>
        </ul>
      </div>
    </div>
    <div class="needsclickWrap">
      <mt-button class='btn sure' type="primary" size="large" @click.native='saveObj'>保存</mt-button>
    </div>

    <!-- 底部打开日期 -->
    <mt-datetime-picker
      ref="startPicker"
      type="date"
      v-model="startPickerValue"
      @confirm="start">
    </mt-datetime-picker>
  </div>
</template>
<script type="text/ecmascript-6">
  import ApiService from '@/services/API-servies'
  import {MessageBox, Button, DatetimePicker} from 'mint-ui';

  export default {
    data() {
      return {
        attachmentInfo : {
            attachmentId:'',
            attachmentUrl:''
        },
        attachmentExtras: [],
        attachmentInvoice: [],
        transTaxList: [],
        feeTaxList: [],
        feeTaxRate: 0,//杂费费率
        transTaxRate: 0,//运费费率
        feeTaxRateStr:"",
        transTaxRateStr:"",
        attchmentType: "",//上传图片类型：0:运费 1:杂费
        startPickerValue: new Date(),
        removeId:[],
        imgList: [],
        showExtrasImg:[],
        dateType:"",//日期操作的运费还是杂费
        dateIndex:"",//操作的是哪一条数据
        transAmount:0.00,
        invoiceTaxAmount:0.00
      }
    },
    created() {
      window.getUploadPictures = this.getUploadPictures;
      window.setUploadPictures = this.setUploadPictures;
      this.getUpload();
    },
    mounted() {
      this.load();
      setTimeout(() => {
        if(this.$isBrower.isAndroid){
            }else if(this.$isBrower.isIos){
                this.setIosTitleType();
            }
          }, 0)
    },
    methods: {
      Qalert() {
        MessageBox({
          title: '提示',
          message: '确定执行此操作?',
          showCancelButton: true
        }).then(action => {
          if (action == 'confirm') {
            console.log('确定')
          } else if (action == 'cancel') {
            console.log('取消')
          }
        })
      }
      ,
      //加载发票信息
      load() {
        ApiService.settle.viewInvoice({
          settleId: this.$route.query.settleId
        }).then((res) => {
          if (res.meta.retCode === '0') {
            console.log(res.data);
            let _listExtras = res.data.attachmentExtras;
            let _listInvoice = res.data.attachmentInvoice;
            let _attachmentExtras = this.attachmentExtras;
            for (var i = _listExtras.length - 1; i >= 0; i--) {
              let _attachmentInfo = {
                    attachmentId: _listExtras[i].attachmentId,
                    attachmentUrl:'http://101.132.40.254' + _listExtras[i].attachmentUrl
                }
              _attachmentExtras.push(_attachmentInfo);
              this.showExtrasImg.push(_attachmentInfo.attachmentUrl);
            }
            let _attachmentInvoice = this.attachmentInvoice;
            this.imgList=[];
            for (var i = _listInvoice.length - 1; i >= 0; i--) {
              let _attachmentObj = {
                    attachmentId: _listInvoice[i].attachmentId,
                    attachmentUrl:'http://101.132.40.254' + _listInvoice[i].attachmentUrl
                }
             // _listInvoice[i].attachmentUrl = 'http://101.132.40.254' + _listInvoice[i].attachmentUrl;
             _attachmentInvoice.push(_attachmentObj);
             this.imgList.push(_attachmentObj.attachmentUrl)
            };
            //this.attachmentExtras = _listExtras;
            //this.attachmentInvoice = _listInvoice;
            this.feeTaxRate = res.data.feeTaxRate;
            this.transTaxRate = res.data.transTaxRate;
            this.transTaxList = res.data.transTaxList;
            this.feeTaxList = res.data.feeTaxList;
            this.feeTaxRateStr=this.feeTaxRate*100+"%";
            this.transTaxRateStr=this.transTaxRate*100+"%";
            this.transAmount=res.data.transAmount;

            this.feeTaxList.forEach(function (b, index) {
              b.invoiceAmount=b.invoiceAmount.toFixed(2);
            });
            this.transTaxList.forEach(function (b, index) {
              b.invoiceAmount=b.invoiceAmount.toFixed(2);
            })
          }
        });
      }
      ,
      //添加运费发票
      addTransInvoice() {
        this.transTaxList.push({
          invoiceNum: "",
          invoiceBoxNum: "",
          invoiceDate: "",
          invoiceTaxAmount:this.defaultTaxAmount() ,
          invoiceAmount: this.transAmount,
        });
      }
      ,
      //添加杂费发票
      addFeeInvoice() {
        this.feeTaxList.push({
          invoiceNum: "",
          invoiceBoxNum: "",
          invoiceDate: "",
          invoiceTaxAmount: "",
          invoiceAmount: "",
        });
      }
      ,
      //移除杂费发票
      removeFeeInvoice(index) {
        this.feeTaxList.splice(index, 1)
      }
      ,
      //移除运费发票
      removeTransInvoice(index) {
        this.transTaxList.splice(index, 1)
      }
      ,
      //移除运费发票

      removeData(_array,_item,_index,val){
        if('' != _item.attachmentId){
          this.removeId.push(_item.attachmentId);
        }
        _array.splice(_index,1);
       if(val == 1){
            let _imgList = this.imgList;
            var index = _imgList.indexOf(_item.attachmentUrl);
            if (index > -1) {
                _imgList.splice(index, 1);
            }
        }else if(val == 2){
            let _showExtrasImg = this.showExtrasImg;
            var index = _showExtrasImg.indexOf(_item.attachmentUrl);
            if (index > -1) {
                _showExtrasImg.splice(index, 1);
            }
        }
      },
      /*removeTransImage(item, index) {
        if('' != _item.attachmentId){
          this.removeId.push(item.attachmentId);
        }
        this.attachmentInvoice.splice(index, 1)

        ApiService.receipt.deleteImage({
          attachmentId: item.attachmentId
        }).then((res) => {
          if (res.meta.retCode === '0') {
            this.attachmentInvoice.splice(index, 1)
          }
        });
      }
      ,*/
      //移除杂费发票
      /*removeFeeImage(item, index) {
        if('' != _item.attachmentId){
          this.removeId.push(item.attachmentId);
        }
        this.attachmentExtras.splice(index, 1)
        ApiService.receipt.deleteImage({
          attachmentId: item.attachmentId
        }).then((res) => {
          if (res.meta.retCode === '0') {
            this.attachmentExtras.splice(index, 1)
          }
        });
      }
      ,*/
      //上传图片
      getUploadPictures(type) {
        this.attchmentType = type;
        if (this.$isBrower.isAndroid) {
          app.getUploadPictures(this.$route.query.settleId,6);
        } else if (this.$isBrower.isIos) {
          this.toUpload();
        }
        /*var img = ["http://101.132.40.254/home/ftp/temp/JS180301173/be336ee9-e4c3-485f-93f0-f89f44d44d6f.png"]
        this.uploadInvoce(img);*/
      },
      toUpload(type) {
        this.attchmentType = type;
        let params = this.$route.query.settleId;
        this.$bridge.callhandler('ToUpload', params, (data) => {
        })
      },
      getUpload() {
        let attchmentType = this.attchmentType+"-"+6;
        this.$bridge.registerhandler('GetUpload', (data) => {
          this.uploadInvoce(data);
        })
      },
      setUploadPictures(res) {
        this.uploadInvoce(res);
      },
      //上传图片
      uploadInvoce(imgSrc) {
        let attchmentType = this.attchmentType;
        let _attachmentInvoice = this.attachmentInvoice;
        if (attchmentType == 0) {
            for (var i = imgSrc.length - 1; i >= 0; i--) {
               let _attachmentInfo = {
                    attachmentId: '',
                    attachmentUrl: imgSrc[i]
                }
               _attachmentInvoice.push(_attachmentInfo);
               this.imgList.push(_attachmentInfo.attachmentUrl)
            }
        }
        if (attchmentType == 1) {
          let _attachmentExtras = this.attachmentExtras;
          for (var i = imgSrc.length - 1; i >= 0; i--) {
              let _attachmentInfo = {
                    attachmentId: '',
                    attachmentUrl:imgSrc[i]
              }
               _attachmentExtras.push(_attachmentInfo);
               this.showExtrasImg.push(_attachmentInfo.attachmentUrl);
          }
        }

       /* ApiService.settle.uploadInvoce({
          settleId: this.$route.query.settleId,
          type: attchmentType,
          source: 1,
          imgSrc: imgSrc
        }).then((res) => {
          if (res.meta.retCode === '0') {
            if (attchmentType == 0) {
              this.attachmentInvoice.push(res.data);
            }
            if (attchmentType == 1) {
              this.attachmentExtras.push(res.data);
            }
          }
        });*/
      },
      //保存发票
      saveObj() {
        let jsonList = [];
        let transTaxRate = this.transTaxRate;
        let feeTaxRate = this.feeTaxRate;
        this.transTaxList.forEach(function (b, index) {
          jsonList.push({
            invoiceNum: b.invoiceNum,
            invoiceBoxNum: b.invoiceBoxNum,
            invoiceDate: b.invoiceDate,
            invoiceTaxAmount: b.invoiceTaxAmount,
            invoiceAmount: b.invoiceAmount,
            invoiceType: "10",
            taxRate: transTaxRate
          })
        });
        this.feeTaxList.forEach(function (b, index) {
          jsonList.push({
            invoiceNum: b.invoiceNum,
            invoiceBoxNum: b.invoiceBoxNum,
            invoiceDate: b.invoiceDate,
            invoiceTaxAmount: b.invoiceTaxAmount,
            invoiceAmount: b.invoiceAmount,
            invoiceType: "20",
            taxRate: feeTaxRate
          })
        });
        ApiService.settle.invoicing({
          settleId: this.$route.query.settleId,
          source: 20,
          attachmentInvoice:JSON.stringify(this.attachmentInvoice),
          attachmentExtras:JSON.stringify(this.attachmentExtras),
          jsonList: JSON.stringify(jsonList),
          removeId:JSON.stringify(this.removeId),
        }).then((res) => {
          if (res.meta.retCode === '0') {
            MessageBox('提示', '保存发票成功').then(action => {
              if (action == 'confirm') {
                localStorage.setItem('localSettleStatus',"40");
                this.$router.push({path: 'settlement'});
              }
            })
          }
        });
      }
      ,
      openPicker(dataType,dateIndex) {
        this.dateType=dataType;
        this.dateIndex=dateIndex;
        this.$refs.startPicker.open()
      },
      start(value) {
        if(this.dateType==0){//运费
          this.transTaxList[this.dateIndex].invoiceDate=this.$moment(value).format("YYYY-MM-DD");
        }
        if(this.dateType==1){//杂费
          this.feeTaxList[this.dateIndex].invoiceDate=this.$moment(value).format("YYYY-MM-DD");;
        }
      },
      change(index, type) {
        if (type == 0) {
          let transTax = this.toDecimal2(this.toDecimal2(this.transTaxList[index].invoiceAmount / (1 + this.transTaxRate)) * this.transTaxRate)
          this.transTaxList[index].invoiceTaxAmount = transTax;
        }
        if (type == 1) {
          let feeTax = (this.feeTaxList[index].invoiceAmount * this.feeTaxRate * 1).toFixed(2)
          this.feeTaxList[index].invoiceTaxAmount = feeTax;
        }
      }
      ,
      defaultTaxAmount(){
        let transTax = this.toDecimal2(this.toDecimal2(this.transAmount / (1 + this.transTaxRate)) * this.transTaxRate);
        this.invoiceTaxAmount = transTax;
      }
      ,
      toDecimal2(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
          return false;
        }
        var f = Math.round(x * 100) / 100;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
          rs = s.length;
          s += '.';
        }
        while (s.length <= rs + 2) {
          s += '0';
        }
        return s;
      },
      //ios 设置头部信息
      setIosTitleType(){
        let params = {
          isReturn: true,
          isSearch: false,
          isTitleSegment:false
        };
        this.$bridge.callhandler('needBarButton', params, (data) => {})
      }
    },
    filters: {},
    components: {
      MtButton: Button,
      MtDatetimePicker: DatetimePicker
    }
  }
</script>
<style scoped lang="less" type="stylesheet/less">
  @import "~common/less/variable";
  @import "~common/less/modules/public.less";
  @import "~common/less/modules/invoice.less";
</style>
